package com.ali.demo.unicom.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ali.demo.unicom.dao.DemoDAO;
import com.ali.demo.unicom.domain.Demo;
import com.ali.demo.unicom.domain.Product;
import com.ali.demo.unicom.ons.ONSHelper;
import com.ali.demo.unicom.ons.ONSTransactionBean;
import com.ali.demo.unicom.service.ProductService;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionChecker;
import com.aliyun.openservices.ons.api.transaction.TransactionStatus;

public class ProductServiceImpl implements ProductService, MessageListener,
		LocalTransactionChecker {

	private static final Logger logger = LoggerFactory
			.getLogger(ProductServiceImpl.class);

	private ONSTransactionBean transactionBean;
	private DemoDAO demoDAO;
	private ProducerBean producerBean;

	public DemoDAO getDemoDAO() {
		return demoDAO;
	}

	public void setDemoDAO(DemoDAO demoDAO) {
		this.demoDAO = demoDAO;
	}

	public ONSTransactionBean getTransactionBean() {
		return transactionBean;
	}

	public void setTransactionBean(ONSTransactionBean transactionBean) {
		this.transactionBean = transactionBean;
	}

	public ProducerBean getProducerBean() {
		return producerBean;
	}

	public void setProducerBean(ProducerBean producerBean) {
		this.producerBean = producerBean;
	}

	public static Logger getLogger() {
		return logger;
	}

	@Override
	public TransactionStatus check(Message arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	// 以下为新增
	@Override
	public void sendProduct(Product product) {
		// TODO Auto-generated method stub
		Message message = new Message();
		message.setTopic("demo_topic");
		message.setTag("DEMO");
		// msg.setKey(String.valueOf(demoID));
		message.setBody(ONSHelper.obj2Body(product));
		producerBean.send(message);
	}

	@Override
	public Action consume(Message msg, ConsumeContext context) {
		switch (msg.getTag()) {
		case "DEM O":
			Demo demo = ONSHelper.body2Obj(msg.getBody(), Demo.class);
			if (logger.isInfoEnabled()) {
				String infomsg = "Demo insert: ID = " + msg.getKey()
						+ ", object = " + demo;
				logger.info(infomsg);
			}
			return Action.CommitMessage;
		default:
			String errmsg = "Unknown message TAG: " + msg.getTag() + ", KEY = "
					+ msg.getKey() + ", msgID = " + msg.getMsgID();
			logger.error(errmsg);
			break;
		}
		return Action.ReconsumeLater;
	}

}
